﻿using System;
using System.Collections.Generic;
using System.Linq;
using SportTraining.Core.Domain;
using SportTraining.MVVM.Model;
using SportTraining.MVVM.View;

namespace SportTraining.MVVM.ViewModel.Impl
{
    public class SectionSelectPageViewModel : PageViewModel<SectionSelectPageViewModel>, ISectionSelectPageViewModel
    {
        private readonly IPaymentProcedureModel model;

        public SectionSelectPageViewModel(IMainWindowViewModel mainWindowViewModel, IPaymentProcedureModel model) : base(mainWindowViewModel)
        {
            this.model = model;

            Forward = new Command(param =>
                                      {
                                          IPayment newPayment = this.model.CreatePayment(SelectedSectionItem.Section);

                                          newPayment.SubscriptionDate = SubscriptionDate;
                                          newPayment.PaymentDate = DateTime.Now;

                                          mainWindowViewModel.SaveObject(KeyConstants.PaymentItemKey, new PaymentItemViewModel(newPayment));

                                          mainWindowViewModel.CurrentPageUri = AppUri.PaymentPage;

                                      }, param => SelectedSectionItem != null);

            Back = new Command(param => mainWindowViewModel.CurrentPageUri = AppUri.MainPage);
        }

        #region Implementation of ISectionSelectPageViewModel

        private List<ISectionItemViewModel> sections;

        public IList<ISectionItemViewModel> Sections
        {
            get
            {
                if (sections == null)
                {
                    sections = new List<ISectionItemViewModel>();

                    var list = model.GetEnableSections();

                    foreach (ISection section in list)
                    {
                        var sectionItemViewModel = new SectionItemViewModel(section);
                        Sections.Add(sectionItemViewModel);
                    }
                }

                return sections;
            }
        }

        public ISectionItemViewModel SelectedSectionItem
        {
            get { return sections.FirstOrDefault(item => item.IsSelected); }
        }

        private DateTime subscriptionDate = DateTime.Now;
        public DateTime SubscriptionDate
        {
            get { return subscriptionDate; }
            set
            {
                subscriptionDate = value;
                FirePropertyChanged(type => type.SubscriptionDate);
            }
        }

        #endregion
    }
}